/*
 * Copyright (c) 2023-2025 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.mybatis.ext.mybatis.extension;

import java.io.Serializable;
import java.util.Collection;
import org.elsfs.cloud.common.mybatis.ext.sql.Join;
import org.elsfs.cloud.common.mybatis.ext.sql.JoinBuilder;
import org.elsfs.cloud.common.mybatis.ext.sql.JoinConditionBuilder;
import org.elsfs.cloud.common.util.lang.StringUtils;

/**
 * JOIN查询拓展接口
 *
 * @param <C> 子类具体类型
 * @param <JB> JOIN构建器类型
 * @param <JCB> JOIN条件构建器类型
 */
public interface JoinWrapper<
        C extends JoinWrapper<C, JB, JCB>,
        JB extends JoinBuilder<JB, JCB, C>,
        JCB extends JoinConditionBuilder<JCB, JB, C>>
    extends Join<C, JB, JCB>, Serializable {

  /** 选择字段分隔符 */
  String FIELD_SEPARATOR = ", ";

  /** 主表别名前缀 */
  String TABLE_ALIAS_PREFIX = "t.";

  /**
   * 获取JOIN的SQL片段
   *
   * @return SQL片段
   */
  String getJoinSqlSegment();

  /**
   * 是否已清空默认的选择字段
   *
   * @return bool
   */
  boolean isClearedDefaultSelectedFields();

  /**
   * 清空默认的选择字段
   *
   * @return this
   */
  C clearDefaultSelectedFields();

  /**
   * 合并SQL选择字段
   *
   * @param existedFields 已存在字段
   * @param newFields 新的选择字段
   * @return 合并后的选择字段
   */
  static String mergeSelectedFields(String existedFields, String[] newFields) {
    if (StringUtils.isNotBlank(existedFields)) {
      return existedFields + FIELD_SEPARATOR + String.join(FIELD_SEPARATOR, newFields);
    } else {
      return String.join(FIELD_SEPARATOR, newFields);
    }
  }

  /**
   * 合并SQL选择字段
   *
   * @param existedFields 已存在字段
   * @param newFields 新的选择字段
   * @return 合并后的选择字段
   */
  static String mergeSelectedFields(String existedFields, Collection<String> newFields) {
    if (StringUtils.isNotBlank(existedFields)) {
      return existedFields + FIELD_SEPARATOR + String.join(FIELD_SEPARATOR, newFields);
    } else {
      return String.join(FIELD_SEPARATOR, newFields);
    }
  }
}
